<template>
    <div class="page-wrap" v-loading="loading">
        <a-page-header @back="handleBack" class="page-header-wrap">
            <template #subTitle> {{ $filters.valToNameFilter('fromSystem', detailData.system) }}—{{ detailData.versionNumber }} </template>
            <template #tags>
                <flexbox>
                    <h-status-tag :status="detailData.status" type="version" class="margin-l-8" />
                    <a-tag color="blue" v-if="detailData.replenishRecord"> 补录 </a-tag>
                </flexbox>
            </template>
            <div class="header-title">
                {{ detailData.versionName }}
            </div>
            <img src="@/assets/images/badge-version.png" style="position: absolute; top: 8px; right: -10px" />
        </a-page-header>
        <version-status :detail="detailData" v-if="detailData.id && !detailData.jiraId"> </version-status>

        <!-- 主体内容 -->
        <div :class="['page-cont', +detailData.status < 3 ? 'normal' : 'abnormal']" v-if="detailData.id">
            <!-- 过程 -->
            <process-bar
                :detail="detailData"
                :testVersionList="testVersionList"
                :stage="stage"
                :hasAuth="hasAuth"
                :stepStatus="processStepStatus"
                :historyList="historyList"
                :relateFileInfo="relateFileInfo"
                :isRelatePro="isRelatePro"
                :isHasWorkComp="isHasWorkComp"
                :testStatus="testStatus"
                :processDisabled="processDisabled"
                :isCanFinishOnline="isCanFinishOnline"
                :isAutoTest="isAutoTest"
                style="margin-bottom: 16px"
                @changeTab="handleChangeTabEmit"
                v-if="!detailData.jiraId"
            />
            <div style="background: #fff">
                <a-tabs :activeKey="activeKey" size="small" @change="handleTabChange">
                    <a-tab-pane :forceRender="true" v-for="(item, index) of showComps" :key="index">
                        <template #tab> {{ item.title }} <FormOutlined v-if="!item.disabled" /></template>
                        <div v-if="item.show" style="padding: 0 24px">
                            <component
                                :ref="setCompsItemRef(item)"
                                :is="item.comName"
                                :detail="{ comName: item.comName, ...detailData }"
                                :testVersionList="testVersionList"
                                :stage="stage"
                                :disabled="item.disabled"
                                :hasAuth="hasAuth"
                                :stepStatus="processStepStatus"
                                :historyList="historyList"
                                :systemInfo="systemInfo"
                                @success="getDetailData"
                                @detailChange="detailChange"
                                @save="handleSave"
                            />
                        </div>
                    </a-tab-pane>
                </a-tabs>
            </div>
        </div>
        <!-- 审核表 -->
        <version-detail-Review ref="versionDetailReviewRef" v-if="showVersionReview" @success="backToWork" />
        <!-- 审核测试报告 -->
        <version-detail-Review-test-report ref="versionDetailReviewTestReportRef" v-if="showVersionReviewTestReport" @success="init" />
        <!-- 实时预览表 -->
        <version-detail-Preview ref="versionDetailPreviewRef" />
    </div>
</template>

<script lang="ts">
import { message } from 'ant-design-vue';
import { allStepStatus } from '@/config/commonData';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import api from '@/api';
import moment from 'moment';
import { useMountedAndActivated } from '@/hooks/common/useMountedAndActivated';
import ProcessBar from './components/ProcessBar.vue';
import BaseInfo from '@/views/version/versionDetail/components/BaseInfo.vue';
import RelateRequire from '@/views/version/versionDetail/components/RelateRequire/index.vue';
import RelateProcess from '@/views/version/versionDetail/components/RelateProcess/index.vue';
import RelateTestProcess from '@/views/version/versionDetail/components/RelateTestProcess/index.vue';
import RelateChange from '@/views/version/versionDetail/components/RelateChange/index.vue';
import RelateFile from '@/views/version/versionDetail/components/RelateFile/index.vue';
import RelateWork from '@/views/version/versionDetail/components/RelateWork/index.vue';
import RelateTime from '@/views/version/versionDetail/components/RelateTime/index.vue';
import VersionStatus from '@/views/version/versionDetail/components/VersionStatus.vue';
import VersionDetailReview from '../versionDetailReview/index.vue';
import versionDetailReviewTestReport from '../versionDetailReviewTestReport/index.vue';
import VersionDetailPreview from '../versionDetailPreview/index.vue';
import { FormOutlined } from '@ant-design/icons-vue';
import { HStatusTag } from '@/components';
import { useDownFile } from '@/hooks/common/useFile';
import store from '@/store';
const allComps = [
    { comName: 'BaseInfo', title: '基本信息' },
    { comName: 'RelateRequire', title: '需求列表' },
    { comName: 'RelateProcess', title: '研发流程' },
    { comName: 'RelateTestProcess', title: '测试信息' },
    { comName: 'RelateChange', title: '变更信息' },
    { comName: 'RelateFile', title: '相关文档' },
    { comName: 'RelateWork', title: '上线工单' },
    { comName: 'RelateTime', title: '排期及完成时间' }
];
import { defineComponent, ref, unref, reactive, toRefs, computed, getCurrentInstance, nextTick, onMounted, onBeforeUnmount } from 'vue';
export default defineComponent({
    name: 'VersionDetail',
    components: {
        BaseInfo,
        RelateRequire,
        RelateProcess,
        RelateTestProcess,
        RelateChange,
        RelateFile,
        RelateWork,
        RelateTime,
        HStatusTag,
        VersionStatus,
        VersionDetailReview,
        versionDetailReviewTestReport,
        VersionDetailPreview,
        FormOutlined,
        ProcessBar
    },
    setup() {
        const { route, router, handleBack } = useRouterApi({
            backQuery: {
                path: '/version/versionList'
            }
        });
        const instance: any = getCurrentInstance();
        const { previewFile } = useDownFile();
        const compsItemRefs: any = reactive({});
        const versionDetailReviewRef = ref<any>();
        const versionDetailPreviewRef = ref<any>();
        const versionDetailReviewTestReportRef = ref<any>();
        const state = reactive<any>({
            form: {},
            processStepStatus: '', //对应流程类型下的某个节点
            loading: false,
            detailData: {},
            historyList: [], //历史记录
            hasAuth: false,
            comps: [],
            activeKey: 0,
            showVersionReview: false,
            showVersionReviewTestReport: false, //预览测试报告
            testVersionList: [],
            systemInfo: {}
        });
        const empId = computed(() => {
            return store.getters.userInfo.employeeDTO.empId;
        });
        const isPM = computed(() => {
            return store.getters.userInfo.employeeDTO.isPM;
        });
        const stage = computed(() => {
            return state.processStepStatus ? allStepStatus[state.processStepStatus] : '待开始';
        });
        // 是否有完成工单模块
        const isHasWorkComp = computed(() => {
            return !!Number(state.systemInfo.isCheckWorkOrder);
        });
        // 是否是外部系统
        const isOutsideSystem = computed(() => {
            return state.detailData.id ? state.detailData.pmpProductDetailDTO.isOutsideSystem === '1' : false;
        });
        // 是否关联需求
        const isRelatePro = computed(() => {
            if (isOutsideSystem.value) {
                return state.detailData.pmpJiraIssueDTOs ? !!state.detailData.pmpJiraIssueDTOs.length : false;
            } else {
                return state.detailData.pmpProductRequires ? !!state.detailData.pmpProductRequires.length : false;
            }
        });
        // 是否自动提测
        const isAutoTest = computed(() => {
            return unref(compsItemRefs.RelateTestProcess)?.isAutoTest;
        });
        const testStatus = computed(() => {
            return unref(compsItemRefs.RelateTestProcess)?.testStatus;
        });
        // 版本流程要交验关联工单的，上线阶段需要判断下是否可以完成
        const isCanFinishOnline = computed(() => {
            if (unref(compsItemRefs.RelateWork)) {
                return unref(compsItemRefs.RelateWork)?.isCanFinish;
            } else {
                return true;
            }
        });
        // 是否上传了必要文档
        const relateFileInfo = computed(() => {
            let isUploadFile = false;
            let connectType = '';
            if (state.detailData.status === '1' && state.detailData.processType !== '1') {
                connectType = '需求文档';
                isUploadFile = !!state.detailData.files.find((item) => item.connectType === connectType && item.status !== 'delete');
            }
            // 基线和产品经理修改
            if (['basicLine', 'productChange'].includes(state.processStepStatus)) {
                connectType = '需求文档';
                isUploadFile = !!state.detailData.files.find((item) => item.connectType === connectType && item.status !== 'delete');
            }
            // 外采
            if (state.processStepStatus === 'outSide') {
                connectType = '更新包';
                isUploadFile = !!state.detailData.files.find((item) => item.connectType === connectType && item.status !== 'delete');
            }
            // 需求测试
            if (state.processStepStatus === 'requireTest' && !state.detailData.pmpTestInformationDTO) {
                connectType = '测试报告';
                isUploadFile = !!state.detailData.files.find((item) => item.connectType === connectType && item.status !== 'delete');
            }
            // 上线
            if (state.processStepStatus === 'requireOnline' && state.detailData.processType === '2') {
                connectType = '更新包';
                isUploadFile = !!state.detailData.files.find((item) => item.connectType === connectType && item.status !== 'delete');
            }
            return {
                isUploadFile,
                connectType
            };
        });
        // 是否显示流程模块
        const processDisabled = computed(() => {
            // 已发布的或者是挂起等节点不显示
            if (+state.detailData.status >= 3) {
                return true;
            } else {
                if (state.historyList.length) {
                    // 是否自动提测
                    if (state.detailData.pmpTestInformationDTO) {
                        // 需求测试和测试经理审核无需判断
                        if (state.detailData.processStatus === '6') {
                            return false;
                        }
                    }
                    // 审批节点操作人不是当前用户的无需显示
                    if (
                        ['basicLine', 'productChange', 'productManagerReview', 'teamLeaderAduit', 'requireOnline'].includes(state.processStepStatus)
                    ) {
                        return !(state.hasAuth || store.getters.userInfo.roles.some((item) => ['产品经理'].includes(item)));
                    } else {
                        return !state.hasAuth;
                    }
                } else {
                    return !store.getters.userInfo.employeeDTO.isPM;
                }
            }
        });
        // 只有创建人和特定流程下可编辑
        const disabled = computed(() => {
            if (+state.detailData.status === 1) {
                return !unref(isPM);
            } else {
                // 流程历史当前操作人或者产品经理
                return !(
                    (state.hasAuth || unref(isPM)) &&
                    [
                        'basicLine',
                        'requireDev',
                        'requireTest',
                        'productChange',
                        'outSide',
                        'productManagerReview',
                        'teamLeaderAduit',
                        'requireOnline'
                    ].includes(state.processStepStatus)
                );
            }
        });

        const showComps = computed(() => {
            console.log('comps', state.comps);
            return state.comps.filter((item) => item.show);
        });
        const setCompsItemRef = (item) => (el) => {
            compsItemRefs[`${item.comName}`] = el;
        };
        // 刷新提测状态
        const refreshTestStatus = async (showMsg = false) => {
            // 有一个接受 2，3
            // 有一个完成 4
            // 全部未接受 1
            const query = {
                id: state.detailData.id
            };
            const { success, moule, errorMsg } = await api.productProcessModel.getRequestInfo(query);
            if (success) {
                // 获取测试版本。判断测试状态
                state.testVersionList = [...moule];
                let status = 0;
                const allRequestStatus: any = [];
                moule.forEach((item: any) => {
                    allRequestStatus.push(item.requestStatus);
                    if (status !== 4) {
                        if ([0, 3].includes(status) && item.acceptStatus === '已驳回') {
                            status = 3;
                        } else if (item.acceptStatus === '已接受' || item.requestStatus === '已中止') {
                            status = 2;
                        } else if (item.acceptStatus === '完成') {
                            status = 4;
                        } else {
                            if (status === 0 || item.acceptStatus === '待审核') {
                                status = 1;
                            }
                        }
                    }
                });
                state.detailData.pmpTestInformationDTO.testStatus = status;
                state.detailData.pmpTestInformationDTO.allRequestStatus = allRequestStatus;
                if (showMsg) {
                    message.success('刷新成功');
                }
            } else {
                message.error(errorMsg);
            }
        };
        // 获取详情接口
        const getDetailData = async (init = false) => {
            const query = {
                id: route.query.id
            };
            const { success, moule, errorMsg } = await api.versionModel.findById(query);

            if (success) {
                const { processType, processStatus, pmpTestInformationDTO, pmpProductDetailDTO } = moule;

                // 如果是外部系统，jira需求
                if (pmpProductDetailDTO && pmpProductDetailDTO.isOutsideSystem === '1') {
                    moule.autoTest = false;
                }
                // jira默认自动提测
                if (moule.jiraId) {
                    moule.autoTest = true;
                }
                // 兼容旧数据
                if (processType === '2') {
                    // 自研，基线后
                    if (processStatus > 3) {
                        if (pmpTestInformationDTO) {
                            moule.autoTest = true;
                        } else {
                            moule.autoTest = false;
                        }
                    }
                }
                // 外采，外采验收后
                if (processType === '1') {
                    if (processStatus > 5) {
                        if (pmpTestInformationDTO) {
                            moule.autoTest = true;
                        } else {
                            moule.autoTest = false;
                        }
                    }
                }

                state.detailData = { ...moule };
                state.detailData.pmpTestInformationDTO && refreshTestStatus();
                init && initComps();
            } else {
                message.error(errorMsg);
            }
            return success;
        };
        // 获取历史记录列表
        const getHistoryList = async () => {
            const query = {
                instanceId: state.detailData.instanceId,
                type: 'version'
            };
            const { success, moule, errorMsg } = await api.historyModel.historyOperationByInstanceId(query);
            if (success) {
                if (moule && moule.length) {
                    state.historyList = [...moule];
                    // 审批节点操作人不是当前用户的无需显示
                    const target = state.historyList[state.historyList.length - 1];
                    if (target) {
                        state.hasAuth = target.assignee.indexOf(store.getters.userInfo.employeeDTO.empId) >= 0;
                    }
                }
            } else {
                message.error(errorMsg);
            }
        };
        // 获取流程状态
        const getProcessStatus = async () => {
            const query = {
                instanceId: state.detailData.instanceId
            };
            const { success, moule } = await api.productProcessModel.processStatus(query);
            if (success) {
                state.processStepStatus = moule;
                state.detailData.taskNode = state.processStepStatus;
                state.detailData.updateByName = store.getters.userInfo.employeeDTO.name;
            }
        };
        // 检测是否填入
        const validateAllForm = async (validateComps: any[], validate = true) => {
            validateComps = validateComps.filter((item) => item);
            let validateInfo: any = {
                res: true
            };
            if (validate) {
                for (let i = 0; i < validateComps.length; i++) {
                    const target = unref(validateComps[i]);
                    if (target?.validate) {
                        validateInfo = await target?.validate();
                    }
                    if (validateInfo.res) {
                        if (target?.form) {
                            state.form = {
                                ...state.form,
                                ...target.form
                            };
                        }
                    } else {
                        const index = showComps.value.findIndex((item) => {
                            if (compsItemRefs[item.comName].detail && compsItemRefs[item.comName].detail.comName) {
                                return compsItemRefs[item.comName].detail.comName === validateComps[i].detail.comName;
                            }
                            return false;
                        });
                        state.activeKey = index;
                        return validateInfo;
                    }
                }
            } else {
                validateComps.forEach((item) => {
                    const target = unref(item);
                    if (target?.form) {
                        state.form = {
                            ...state.form,
                            ...target.form
                        };
                    }
                });
            }
            return validateInfo;
        };
        // 保存
        const handleSave = async (type: number) => {
            state.loading = true;
            let requestApi: Nullable<PromiseFn> = null;
            let validateInfo: Recordable = {};
            switch (type) {
                // 未发起评审时的版本修改
                case 1:
                    requestApi = api.versionModel.save;
                    break;
                // 发起评审
                case 2:
                    requestApi = api.productProcessModel.startProcess;
                    break;
                // 更新流程
                case 3:
                    requestApi = api.productProcessModel.auditProcess;
                    break;
                // 存储基本信息
                case 5: // 存储baseInfo
                case 6: // 存储baseInfo和测试流程
                case 7: // 存储排期完成时间
                case 8: // 相关文档
                case 9:
                    requestApi = api.versionModel.save;
                    break;
            }
            // 不同操作校验不同模块
            if (type === 1) {
                validateInfo = await validateAllForm([compsItemRefs.BaseInfo, compsItemRefs.RelateProcess, compsItemRefs.RelateTestProcess], false);
            } else if (type === 5) {
                validateInfo = await validateAllForm([compsItemRefs.BaseInfo]);
            } else if (type === 6) {
                validateInfo = await validateAllForm([compsItemRefs.BaseInfo, compsItemRefs.RelateProcess]);
            } else if (type === 7) {
                validateInfo = await validateAllForm([compsItemRefs.RelateTime]);
            } else if (type === 8) {
                validateInfo = await validateAllForm([compsItemRefs.RelateFile]);
            } else if (type === 9) {
                validateInfo = await validateAllForm([compsItemRefs.RelateProcess]);
            } else {
                validateInfo = await validateAllForm([
                    compsItemRefs.BaseInfo,
                    compsItemRefs.RelateRequire,
                    compsItemRefs.RelateFile,
                    compsItemRefs.RelateProcess,
                    compsItemRefs.RelateTestProcess,
                    compsItemRefs.RelateTime
                ]);
            }

            if (validateInfo.res) {
                let query = {
                    ...state.form,
                    catalogCode: Array.isArray(state.form.catalogCode)
                        ? state.form.catalogCode[state.form.catalogCode.length - 1]
                        : state.form.catalogCode
                };
                // 非暂存需要将所有数据传给后台
                if (type !== 4) {
                    query = {
                        ...state.detailData,
                        ...query
                    };
                }
                // 上线需要把工单结束时间赋值给实际上线时间
                if (type === 3 && state.processStepStatus === 'requireOnline') {
                    if (unref(compsItemRefs.RelateWork)) {
                        query.onlineRealTime = unref(compsItemRefs.RelateWork)?.firstList[0].orderResultTime + ':00';
                    }
                }
                // console.log(query);
                query.processStatus = state.detailData.processStatus;
                const { success, errorMsg } = await (requestApi as PromiseFn)(query);
                if (success) {
                    message.success('操作成功');
                    if (type === 7) {
                        getDetailData(true);
                    } else {
                        // 操作成功后的跳转
                        if (state.processStepStatus) {
                            init(); // 重新初始化
                        } else {
                            // 发起评审跳转到列表
                            if (type === 2) {
                                router.push({
                                    path: '/version/versionList'
                                });
                            } else {
                                getDetailData(true);
                            }
                        }
                        // 如果是上线节点
                        if (type === 3 && state.processStepStatus === 'requireOnline') {
                            const query = {
                                id: state.detailData.id,
                                devType: state.detailData.processType
                            };
                            const { success, errorMsg } = await api.versionStatisticsModel.startProcess(query);
                            if (!success) {
                                message.error(errorMsg);
                            }
                        }
                    }
                    // 释放旧数据
                    state.form = {};
                } else {
                    message.error(errorMsg);
                }
            } else {
                validateInfo.errorMsg && message.error(validateInfo.errorMsg);
            }
            state.loading = false;
        };
        const detailChange = (data: Recordable) => {
            state.detailData = {
                ...state.detailData,
                ...data
            };
        };
        // 动态判断模块是否可编辑
        const checkIsDisabled = (name: string) => {
            // 上线都不可编辑
            if (+state.detailData.status >= 3 || state.detailData.jiraId) {
                return true;
            }
            // 基本信息
            if (name === 'BaseInfo') {
                // state.detailData.createUserEmpId === unref(empId)
                return !(unref(isPM) && +state.detailData.status < 3);
            }
            // 需求列表
            else if (name === 'RelateRequire') {
                return unref(disabled);
            }
            // 排期及完成时间
            else if (name === 'RelateTime') {
                return !(
                    store.getters.userInfo.roles.some((item) => ['产品经理', '测试经理', '研发经理', '项目经理', 'admin'].includes(item)) &&
                    +state.detailData.status < 3
                );
            }
            // 测试信息
            else if (name === 'RelateTestProcess') {
                if (+state.detailData.status === 1 || (state.detailData.processStatus && +state.detailData.processStatus >= 8)) {
                    return true;
                }
                const { processType, processStatus, pmpTestInformationDTO } = state.detailData;
                // 外部系统
                if (isOutsideSystem.value) {
                    return true;
                }
                // 内部系统
                let res = true;
                if (unref(relateFileInfo).connectType) {
                    res = !((state.hasAuth || unref(isPM)) && unref(isRelatePro) && unref(relateFileInfo).isUploadFile);
                } else {
                    res = !((state.hasAuth || unref(isPM)) && unref(isRelatePro));
                }
                // 自研
                if (processType === '2') {
                    if (+processStatus < 3) {
                        return true;
                    } else if (+processStatus > 3) {
                        if (!pmpTestInformationDTO) {
                            return true;
                        } else {
                            return res;
                        }
                    } else {
                        return res;
                    }
                }
                // 外采
                if (processType === '1') {
                    if (+processStatus < 5) {
                        return true;
                    } else if (+processStatus > 5) {
                        if (!pmpTestInformationDTO) {
                            return true;
                        } else {
                            return res;
                        }
                    } else {
                        return res;
                    }
                }
            }
            // 相关文档
            else if (name === 'RelateFile') {
                if (
                    [
                        'basicLine',
                        'outSide',
                        'requireTest',
                        'productChange',
                        'requireDev',
                        'productManagerReview',
                        'teamLeaderAduit',
                        'requireOnline'
                    ].includes(state.processStepStatus)
                ) {
                    return false;
                } else {
                    return !unref(isPM);
                }
            }
            // 研发流程
            else if (name === 'RelateProcess') {
                // 状态是待开始
                if (state.detailData.status === '1') {
                    // return !(state.detailData.createUserEmpId === unref(empId));
                    return !unref(isPM);
                }
                // 确定需求基线,产品经理修改,验收上线修改绑定产品需求
                else if (
                    ['basicLine', 'productChange', 'productManagerReview', 'teamLeaderAduit', 'requireOnline'].includes(state.processStepStatus)
                ) {
                    return !(state.hasAuth || unref(isPM));
                } else {
                    return !state.hasAuth;
                }
            } else {
                return true;
            }
        };
        //退回到工作台
        const backToWork = () => {
            router.push({
                path: '/workbench'
            });
        };
        // 检测是否有改动
        const hasDiff = (compName = 'BaseInfo') => {
            const form = unref(compsItemRefs[compName]).form;
            for (const key in form) {
                // 预计交付时间只比较日期即可
                if (key === 'expectTime') {
                    const res = moment(form.expectTime).isSame(state.detailData.expectTime, 'day');
                    if (!res) {
                        return true;
                    }
                } else if (key !== 'pmpProductLineCalendarDTO' && key !== 'pmpVersionManagementDTO' && form[key] !== state.detailData[key]) {
                    console.log(key, form[key], state.detailData[key]);
                    return true;
                }
            }
            return false;
        };
        const handleChangeTabEmit = () => {
            const index = showComps.value.findIndex((item) => item.title === '相关文档');
            handleTabChange(index);
        };
        const handleTabChange = (val) => {
            if (state.activeKey === 0 && !unref(showComps)[state.activeKey].disabled) {
                unref(compsItemRefs.BaseInfo)
                    .validate()
                    .then(({ res }) => {
                        if (res) {
                            if (hasDiff()) {
                                message.warning('请保存改动过的基本信息');
                            } else {
                                const index = showComps.value.findIndex((item) => {
                                    return item.comName === val;
                                });
                                if (index >= 0) {
                                    state.activeKey = index;
                                } else {
                                    state.activeKey = val;
                                }
                            }
                        }
                    });
            } else if (state.activeKey === 6 && !unref(showComps)[state.activeKey].disabled) {
                if (hasDiff('RelateTime')) {
                    message.warning('请保存改动过的基本信息');
                } else {
                    state.activeKey = val;
                }
            }
            // 需求测试
            else if (val === 5 && !unref(relateFileInfo).isUploadFile) {
                // 寻找更新包
                state.activeKey = val;
                const doms: any = document.getElementsByClassName('file-cont-body');
                for (let i = 0; i < doms.length; i++) {
                    const dom: any = doms[i];
                    if (dom.dataset.title === unref(relateFileInfo).connectType) {
                        nextTick(() => {
                            doms[i].scrollIntoView({ block: 'center', inline: 'center' });
                        });
                    }
                }
            }
            // 上线
            else if (val === 5 && state.processStepStatus === 'requireOnline' && !unref(relateFileInfo).isUploadFile) {
                // 寻找更新包
                state.activeKey = val;
                const doms = document.getElementsByClassName('file-cont-body');
                const dom = doms[doms.length - 4];
                dom.scrollIntoView({ block: 'center', inline: 'center' });
            } else {
                const index = showComps.value.findIndex((item) => {
                    return item.comName === val;
                });
                if (index >= 0) {
                    state.activeKey = index;
                } else {
                    state.activeKey = val;
                }
            }
        };
        const handlePreview = (type: number) => {
            if (type === 0) {
                unref(versionDetailPreviewRef)?.open();
            } else {
                let connectType = '产品内部评审记录';
                if (state.processStepStatus === 'productManagerReview') {
                    connectType = '团队长审核记录';
                }
                if (state.historyList[state.historyList.length - 2].taskName === '研发评审') {
                    connectType = '研发评审记录';
                }
                const files = state.detailData.files.filter((item) => item.connectType === connectType);
                files.length && previewFile(files[files.length - 1]);
            }
        };

        const handleShowReview = () => {
            state.showVersionReview = true;
            nextTick(() => {
                unref(versionDetailReviewRef).open();
            });
        };
        const handleShowReviewTestReport = () => {
            state.showVersionReviewTestReport = true;
            nextTick(() => {
                unref(versionDetailReviewTestReportRef).open(state.detailData);
            });
        };
        // 批量拉取工时
        const handleGetJiraWorkInfo = async () => {
            const list = state.detailData.pmpProductRequires.filter((item) => item.jiraUrl);
            if (list.length) {
                const newList = list.map((item) => {
                    const { id, requireSystem, issueKey } = item;
                    return { id, requireSystem, issueKey };
                });
                const { success, errorMsg, errorCode } = await api.jiraModel.syncWorkLogFromJira([...newList]);
                if (success) {
                    message.success('批量拉取成功');
                } else {
                    if (errorCode === '008') {
                        message.error('请勿重复提交！');
                    } else {
                        message.error(errorMsg);
                    }
                }
                return success;
            } else {
                return false;
            }
        };
        const handleNextProcess = (query) => {
            const comp = unref(unref(unref(compsItemRefs.RelateProcess).checkPrecessRef).comRef);
            // 产品经理修改
            if (state.processStepStatus && state.processStepStatus === 'productChange') {
                comp.handleSave(query.type, query.pass);
            } else if (state.processStepStatus && state.processStepStatus === 'productManagerReview') {
                handleSave(3);
            } else if (state.processStepStatus && state.processStepStatus === 'requireOnline') {
                // 批量拉取工时
                // 外部系统
                if (isOutsideSystem.value) {
                    const issueIds = '';
                    if (state.detailData.pmpJiraIssueDTOs && state.detailData.pmpJiraIssueDTOs.length) {
                        state.detailData.pmpJiraIssueDTOs.map((item) => item.id).join(',');
                    }
                    api.jiraModel
                        .refreshIssueFromJira({
                            issueIds,
                            systemId: state.detailData.system
                        })
                        .then((Success) => {
                            if (Success) {
                                handleSave(3);
                            }
                        });
                }
                // 内部系统
                else {
                    handleGetJiraWorkInfo().then((res) => {
                        handleSave(3);
                    });
                }
            } else {
                comp.handleSave(query.type);
            }
        };
        const handleDoneTask = async () => {
            const { success, errorMsg } = await api.versionModel.updateVersion({
                ...state.detailData,
                nodeFlg: '1',
                autoTest: unref(isAutoTest)
            });
            if (success) {
                getDetailData();
            } else {
                message.error(errorMsg);
            }
        };

        const initComps = () => {
            state.comps = allComps.map((item) => {
                if (item.comName === 'RelateWork') {
                    // 上线工单
                    return {
                        ...item,
                        show: !!Number(state.systemInfo.isCheckWorkOrder),
                        disabled: checkIsDisabled(item.comName)
                    };
                } else {
                    return {
                        ...item,
                        show: true,
                        disabled: checkIsDisabled(item.comName)
                    };
                }
            });
        };
        // 获取系统详情
        const getSystemInfo = async () => {
            const query = {
                id: state.detailData.system
            };
            // 获取系统信息
            const { success, moule } = await api.productDetailModel.findById(query);
            if (success) {
                state.systemInfo = {
                    ...moule
                };
            }
        };
        const init = async () => {
            state.loading = true;
            const res = await getDetailData();
            if (res) {
                await getSystemInfo();
                // 进行中,才获取历史记录
                if (!state.detailData.replenishRecord) {
                    if (+state.detailData.status > 1 && +state.detailData.status <= 4 && !state.detailData.jiraId) {
                        await getHistoryList();
                    }
                    // 进行中调流程节点
                    if (state.detailData.status === '2' && !state.detailData.jiraId) {
                        await getProcessStatus();
                    }
                    // 待开始
                    if (state.detailData.status === '1') {
                        state.hasAuth = state.detailData.createUserEmpId === unref(empId);
                    }
                }
                initComps();
                // 当前展示模块
                if (state.detailData.status !== '2') {
                    state.activeKey = 0;
                } else {
                    if (+state.detailData.stage >= 6) {
                        if (!unref(isRelatePro)) {
                            state.activeKey = 1;
                        } else if (unref(relateFileInfo).connectType && !unref(relateFileInfo).isUploadFile) {
                            state.activeKey = 2;
                        } else if (state.processStepStatus === 'requireOnline') {
                            state.activeKey = 6;
                        } else {
                            state.activeKey = 3;
                        }
                    } else {
                        state.activeKey = 2;
                    }
                }
            }
            state.loading = false;
        };
        onMounted(() => {
            instance.proxy.$mitt.on('updateVersionDetail', () => {
                init(); // 重新初始化
            });
            instance.proxy.$mitt.on('refreshTestStatus', (showMsg) => {
                refreshTestStatus(showMsg); //
            });
            instance.proxy.$mitt.on('showVersionReview', () => {
                state.showVersionReview = true;
                nextTick(() => {
                    unref(versionDetailReviewRef).open();
                });
            });
        });
        onBeforeUnmount(() => {
            instance.proxy.$mitt.all.delete('updateVersionDetail');
            instance.proxy.$mitt.all.delete('showVersionReview');
            instance.proxy.$mitt.all.delete('refreshTestStatus');
        });
        useMountedAndActivated(init, false);
        init();
        return {
            ...toRefs(state),
            setCompsItemRef,
            versionDetailReviewRef,
            versionDetailPreviewRef,
            versionDetailReviewTestReportRef,
            disabled,
            showComps,
            empId,
            getDetailData,
            handleSave,
            handleBack,
            detailChange,
            handleTabChange,
            handlePreview,

            stage,
            isRelatePro,
            relateFileInfo,
            handleShowReview,
            handleShowReviewTestReport,
            processDisabled,
            handleNextProcess,

            isAutoTest,
            testStatus,
            handleDoneTask,

            backToWork,
            isHasWorkComp,
            isCanFinishOnline,

            init,
            handleChangeTabEmit
        };
    }
});
</script>
<style lang="less" scoped >
.page-wrap {
    position: relative;
    height: 100%;
    ::v-deep(.ant-steps) {
        margin-top: 0 !important;
    }
    ::v-deep(.page-top) {
        min-height: 60px !important;
        padding-top: 24px;
        position: relative;
        &::before {
            content: '';
            position: absolute;
            width: 6px;
            height: calc(100% + 1px);
            background: #fb7555;
            top: -1px;
            left: 0;
            z-index: 120;
        }
    }
    .page-header-wrap {
        position: sticky;
        top: 0;
        z-index: 9;
        border-bottom: 1px solid #f1f1f1;
        border-top: 1px solid #f1f1f1;
        background: #fff;
        &::before {
            content: '';
            position: absolute;
            width: 6px;
            height: 100%;
            background: #fb7555;
            top: 0;
            left: 0;
            z-index: 120;
        }
    }
    .header-title {
        font-size: 20px;
        color: @title-font-color;
        font-weight: bold;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .page-cont {
        margin-top: 6px;
        position: relative;
        ::v-deep(.ant-tabs-nav-wrap) {
            padding: 8px 12px 8px 12px;
        }
    }

    .normal {
        // height: calc(100vh - 415px);
        // ::v-deep(.ant-tabs-tabpane) {
        //     height: calc(100vh - 488px);
        //     overflow-y: auto;
        // }
    }
    .abnormal {
        // height: calc(100vh - 299px);
        // ::v-deep(.ant-tabs-tabpane) {
        //     height: calc(100vh - 372px);
        //     overflow-y: auto;
        // }
    }
}
</style>